package com.bite.system.Service.ServiceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import Constants.JwtConstants;
import Utils.JwtUtil;
import com.bite.common.security.domain.LoginUser;
import com.bite.common.security.enums.UserType;
import com.bite.system.Mapper.SysUserMapper;
import com.bite.system.Service.SysUserService;
import com.bite.system.Utils.BCryptUtils;
import com.bite.system.VO.SysUserVO;
import com.bite.system.domain.SysUser;
import com.bite.system.DTO.SysUserDTO;
import domain.MyThreadLocal;
import domain.R;
import enums.ResultCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public R<Object> login(SysUserDTO sysUserDTO) {
        LambdaQueryWrapper<SysUser> eq = new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserDTO.getUserAccount());
        SysUser sysUser = sysUserMapper.selectOne(eq);
        //当查询数据的信息为null时，则用户不存在
        if (sysUser == null){
            return R.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (BCryptUtils.matchesPassword(sysUserDTO.getPassword(), sysUser.getPassword())){

            Map<String,Object> map = new HashMap<>();

            String userKey = UUID.randomUUID().toString();

            map.put(JwtConstants.USER_ID,sysUser.getUserId());

            map.put(JwtConstants.USER_KEY,userKey);

            //生成token
            String token = JwtUtil.createJWT(map, secret);

            //将重要信息放置到redis中

            LoginUser loginUser = new LoginUser(UserType.ADMIN_TYPE.getIdentity());
            //将对象格式转换为字符串格式

            String loginUserStr = JSONUtil.toJsonStr(loginUser);
            stringRedisTemplate.opsForValue().set(userKey,loginUserStr,JwtConstants.EXPIRATION, TimeUnit.MINUTES);


            return R.success(token, ResultCode.SUCCESS);
        }
        //查询密码错误
        return R.failed(ResultCode.FAILED_LOGIN);

    }

    @Override
    public R<SysUserVO> info() {
        //先获取当前用户ID
        String userID = MyThreadLocal.get();
        //根据用户ID查询用户信息
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getNick)
                .eq(SysUser::getUserId, userID);
        SysUser sysUser = sysUserMapper.selectOne(lqw);
        SysUserVO sysUserVO = BeanUtil.copyProperties(sysUser, SysUserVO.class);
        //返回用户nick信息
        return R.success(sysUserVO);
    }

    @Override
    public R<Void> logout(String token) {
        if (token == null){
            throw new RuntimeException("token不能为空");
        }
        Claims claims = JwtUtil.parseJWT(token, secret);
        String userKey = claims.get(JwtConstants.USER_KEY).toString();
        Boolean delete = stringRedisTemplate.delete(userKey);
        if (Boolean.TRUE.equals(delete)){
            return R.success();
        }
        return R.failed();
    }


}
